import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

public class MD5Util {

    // MD5加密方法
    public static String md5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    // MD5加盐加密方法
    public static String md5WithSalt(String input, String salt) throws NoSuchAlgorithmException {
        String saltedInput = input + salt;
        return md5(saltedInput);
    }

    // MD5多次加密
    public static String md5MultipleTimes(String input, int times) throws NoSuchAlgorithmException {
        String result = input;
        for (int i = 0; i < times; i++) {
            result = md5(result);
        }
        return result;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String input = "hello";
        String salt = "randomSalt";

        // MD5加密
        System.out.println("MD5: " + md5(input));

        // MD5加盐加密
        System.out.println("MD5 with Salt: " + md5WithSalt(input, salt));

        // MD5多次加密
        System.out.println("MD5 Multiple Times: " + md5MultipleTimes(input, 3));
    }
}
